<template>
  <div class="community-container">
    <n-card class="community-card">
      <template #header>
        <div class="card-header">
          <h1>创作社区</h1>
          <div class="search-box">
            <n-input v-model:value="searchQuery" placeholder="搜索作品..." clearable>
              <template #prefix>
                <n-icon><SearchOutline /></n-icon>
              </template>
            </n-input>
            <n-button type="primary" @click="search">搜索</n-button>
          </div>
        </div>
      </template>
      
      <div class="content-layout">
        <div class="works-section">
          <div class="filter-bar">
            <n-tabs v-model:value="activeTab" type="line" animated>
              <n-tab-pane name="recommend" tab="推荐" />
              <n-tab-pane name="newest" tab="最新" />
              <n-tab-pane name="popular" tab="热门" />
              <n-tab-pane name="following" tab="关注" />
            </n-tabs>
            
            <n-space class="filter-options">
              <n-select
                v-model:value="selectedCategory"
                :options="categoryOptions"
                placeholder="分类"
                style="width: 120px"
              />
              <n-select
                v-model:value="selectedDuration"
                :options="durationOptions"
                placeholder="时长"
                style="width: 120px"
              />
              <n-select
                v-model:value="selectedTime"
                :options="timeOptions"
                placeholder="时间范围"
                style="width: 120px"
              />
            </n-space>
          </div>
          
          <div class="works-grid">
            <div v-for="work in filteredWorks" :key="work.id" class="work-card" @click="viewWorkDetail(work.id)">
              <div class="work-thumbnail">
                <img :src="work.thumbnail" alt="作品缩略图">
                <div class="work-duration">{{ formatDuration(work.duration) }}</div>
                <div class="play-icon">
                  <n-icon size="24"><PlayCircleOutline /></n-icon>
                </div>
              </div>
              <div class="work-info">
                <h3 class="work-title">{{ work.title }}</h3>
                <div class="work-meta">
                  <div class="creator" @click.stop="viewCreatorProfile(work.creatorId)">
                    <img :src="work.creatorAvatar" alt="创作者头像" class="creator-avatar">
                    <span class="creator-name">{{ work.creatorName }}</span>
                  </div>
                  <div class="stats">
                    <span><n-icon><EyeOutline /></n-icon> {{ formatNumber(work.views) }}</span>
                    <span><n-icon><ThumbsUpOutline /></n-icon> {{ formatNumber(work.likes) }}</span>
                  </div>
                </div>
                <div class="work-time">{{ formatTime(work.publishTime) }}</div>
              </div>
            </div>
          </div>
          
          <div class="pagination">
            <n-pagination
              v-model:page="currentPage"
              :page-count="totalPages"
              :page-size="pageSize"
              :page-slot="5"
              show-quick-jumper
            />
          </div>
        </div>
        
        <div class="sidebar">
          <div class="sidebar-section">
            <h3>推荐创作者</h3>
            <div class="creator-list">
              <div v-for="creator in recommendedCreators" :key="creator.id" 
                class="creator-item" @click="viewCreatorProfile(creator.id)">
                <img :src="creator.avatar" alt="创作者头像" class="creator-avatar">
                <div class="creator-info">
                  <div class="creator-name">{{ creator.name }}</div>
                  <div class="creator-followers">{{ formatNumber(creator.followers) }} 粉丝</div>
                </div>
                <n-button size="tiny" type="primary" ghost @click.stop="followCreator(creator.id)" 
                  :disabled="creator.isFollowing">
                  {{ creator.isFollowing ? '已关注' : '关注' }}
                </n-button>
              </div>
            </div>
          </div>
          
          <div class="sidebar-section">
            <h3>热门标签</h3>
            <div class="tag-cloud">
              <n-space>
                <n-tag 
                  v-for="tag in popularTags" 
                  :key="tag.id"
                  :type="tag.type"
                  size="medium"
                  round
                  @click="searchByTag(tag.name)"
                >
                  {{ tag.name }} ({{ tag.count }})
                </n-tag>
              </n-space>
            </div>
          </div>
          
          <div class="sidebar-section">
            <h3>社区活动</h3>
            <div class="activity-list">
              <div v-for="activity in communityActivities" :key="activity.id" class="activity-item">
                <div class="activity-banner">
                  <img :src="activity.banner" alt="活动横幅">
                </div>
                <div class="activity-info">
                  <div class="activity-title">{{ activity.title }}</div>
                  <div class="activity-time">{{ activity.timeRange }}</div>
                  <n-button size="small" type="primary" @click="viewActivity(activity.id)">
                    查看详情
                  </n-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  NCard,
  NTabs,
  NTabPane,
  NInput,
  NButton,
  NSelect,
  NPagination,
  NSpace,
  NIcon,
  NTag
} from 'naive-ui'
import {
  SearchOutline,
  PlayCircleOutline,
  EyeOutline,
  ThumbsUpOutline
} from '@vicons/ionicons5'

// 定义接口
interface Creator {
  id: string;
  name: string;
  avatar: string;
  followers: number;
  isFollowing: boolean;
}

interface Tag {
  id: string;
  name: string;
  count: number;
  type: 'default' | 'success' | 'info' | 'warning' | 'error' | 'primary';
}

interface Activity {
  id: string;
  title: string;
  banner: string;
  timeRange: string;
  status: 'ongoing' | 'upcoming' | 'ended';
}

interface Work {
  id: string;
  title: string;
  thumbnail: string;
  duration: number;
  creatorId: string;
  creatorName: string;
  creatorAvatar: string;
  views: number;
  likes: number;
  publishTime: Date;
}

const router = useRouter()

// 搜索与筛选
const searchQuery = ref('')
const activeTab = ref('recommend')
const selectedCategory = ref(null)
const selectedDuration = ref(null)
const selectedTime = ref(null)
const currentPage = ref(1)
const pageSize = ref(12)
const totalPages = ref(10)

// 分类选项
const categoryOptions = [
  { label: '全部', value: null },
  { label: '搞笑', value: 'funny' },
  { label: '动画', value: 'animation' },
  { label: '教程', value: 'tutorial' },
  { label: '故事', value: 'story' },
  { label: '音乐', value: 'music' }
]

// 时长选项
const durationOptions = [
  { label: '全部', value: null },
  { label: '短片 (<1分钟)', value: 'short' },
  { label: '中等 (1-5分钟)', value: 'medium' },
  { label: '长片 (>5分钟)', value: 'long' }
]

// 时间范围选项
const timeOptions = [
  { label: '全部时间', value: null },
  { label: '今日', value: 'today' },
  { label: '本周', value: 'week' },
  { label: '本月', value: 'month' },
  { label: '今年', value: 'year' }
]

// 作品列表
const works = ref<Work[]>([])

// 过滤后的作品
const filteredWorks = computed(() => {
  // 实际项目中，这里会根据筛选条件过滤数据
  return works.value
})

// 推荐创作者
const recommendedCreators = ref<Creator[]>([])

// 热门标签
const popularTags = ref<Tag[]>([
  { id: 'tag-1', name: '搞笑', count: 1265, type: 'success' as const },
  { id: 'tag-2', name: '动画', count: 986, type: 'info' as const },
  { id: 'tag-3', name: '沙雕', count: 754, type: 'warning' as const },
  { id: 'tag-4', name: '皮影', count: 632, type: 'error' as const },
  { id: 'tag-5', name: '创意', count: 521, type: 'success' as const },
  { id: 'tag-6', name: '短片', count: 498, type: 'info' as const },
  { id: 'tag-7', name: '配音', count: 387, type: 'warning' as const },
  { id: 'tag-8', name: '音乐', count: 356, type: 'error' as const },
  { id: 'tag-9', name: '趣味', count: 329, type: 'success' as const },
  { id: 'tag-10', name: '教程', count: 298, type: 'info' as const }
])

// 社区活动
const communityActivities = ref<Activity[]>([])

// 搜索
function search() {
  // 实际项目中，这里会调用API搜索
  console.log('Searching for:', searchQuery.value)
}

// 按标签搜索
function searchByTag(tag: string) {
  searchQuery.value = tag
  search()
}

// 查看作品详情
function viewWorkDetail(id: string) {
  router.push(`/work-detail/${id}`)
}

// 查看创作者资料
function viewCreatorProfile(id: string) {
  router.push(`/user-profile/${id}`)
}

// 关注创作者
function followCreator(id: string) {
  // 实际项目中，这里会调用API关注创作者
  const creator = recommendedCreators.value.find(c => c.id === id)
  if (creator) {
    creator.isFollowing = true
    creator.followers++
  }
}

// 查看活动
function viewActivity(id: string) {
  // 实际项目中，这里会跳转到活动详情页
  console.log('Viewing activity:', id)
}

// 格式化数字
function formatNumber(num: number): string {
  if (num >= 10000) {
    return (num / 10000).toFixed(1) + '万'
  }
  return num.toString()
}

// 格式化时长
function formatDuration(seconds: number): string {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = seconds % 60
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 格式化时间
function formatTime(date: Date): string {
  // 简单格式化，实际项目中可能需要更复杂的逻辑
  return `${date.getMonth() + 1}月${date.getDate()}日`
}

// 生成测试数据
function generateMockData() {
  // 生成作品数据
  const mockWorks: Work[] = []
  for (let i = 1; i <= 20; i++) {
    mockWorks.push({
      id: `work-${i}`,
      title: `皮影作品${i}: 有趣的沙雕动画`,
      thumbnail: `https://picsum.photos/id/${i + 100}/300/180`,
      duration: Math.floor(Math.random() * 300) + 60, // 60-360秒
      creatorId: `creator-${Math.floor(Math.random() * 5) + 1}`,
      creatorName: `创作者${Math.floor(Math.random() * 5) + 1}`,
      creatorAvatar: `https://randomuser.me/api/portraits/${Math.random() > 0.5 ? 'men' : 'women'}/${Math.floor(Math.random() * 50) + 1}.jpg`,
      views: Math.floor(Math.random() * 10000) + 1000,
      likes: Math.floor(Math.random() * 1000) + 100,
      publishTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 86400000) // 0-30天前
    })
  }
  works.value = mockWorks
  
  // 生成推荐创作者
  recommendedCreators.value = [
    {
      id: 'creator-1',
      name: '沙雕动画师',
      avatar: 'https://randomuser.me/api/portraits/men/1.jpg',
      followers: 5824,
      isFollowing: false
    },
    {
      id: 'creator-2',
      name: '皮影大师',
      avatar: 'https://randomuser.me/api/portraits/women/2.jpg',
      followers: 3421,
      isFollowing: true
    },
    {
      id: 'creator-3',
      name: '动画达人',
      avatar: 'https://randomuser.me/api/portraits/men/3.jpg',
      followers: 2876,
      isFollowing: false
    },
    {
      id: 'creator-4',
      name: '趣味动画',
      avatar: 'https://randomuser.me/api/portraits/women/4.jpg',
      followers: 1982,
      isFollowing: false
    },
    {
      id: 'creator-5',
      name: '创意工作室',
      avatar: 'https://randomuser.me/api/portraits/men/5.jpg',
      followers: 9874,
      isFollowing: false
    }
  ]
  
  // 生成社区活动
  communityActivities.value = [
    {
      id: 'activity-1',
      title: '2023皮影动画大赛',
      banner: 'https://picsum.photos/id/237/300/100',
      timeRange: '2023.5.1 - 2023.6.30',
      status: 'ongoing'
    },
    {
      id: 'activity-2',
      title: '创意配音挑战赛',
      banner: 'https://picsum.photos/id/238/300/100',
      timeRange: '2023.7.15 - 2023.8.15',
      status: 'upcoming'
    },
    {
      id: 'activity-3',
      title: '沙雕动画创作营',
      banner: 'https://picsum.photos/id/239/300/100',
      timeRange: '2023.9.1 - 2023.9.30',
      status: 'upcoming'
    }
  ]
}

// 生命周期钩子
onMounted(() => {
  generateMockData()
})
</script>

<style lang="scss" scoped>
.community-container {
  padding: 20px;
  
  .community-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h1 {
        margin: 0;
        font-size: 24px;
      }
      
      .search-box {
        display: flex;
        gap: 10px;
        width: 300px;
      }
    }
  }
  
  .content-layout {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 20px;
    
    .works-section {
      .filter-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 20px;
        
        .filter-options {
          flex-shrink: 0;
        }
      }
      
      .works-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
        gap: 16px;
        margin-bottom: 20px;
        
        .work-card {
          border-radius: 8px;
          overflow: hidden;
          background-color: var(--card-color);
          transition: transform 0.3s ease, box-shadow 0.3s ease;
          cursor: pointer;
          
          &:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            
            .play-icon {
              opacity: 1;
              transform: translate(-50%, -50%) scale(1.2);
            }
          }
          
          .work-thumbnail {
            position: relative;
            height: 160px;
            overflow: hidden;
            
            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
              transition: transform 0.3s ease;
            }
            
            .work-duration {
              position: absolute;
              bottom: 8px;
              right: 8px;
              background-color: rgba(0, 0, 0, 0.7);
              color: white;
              padding: 2px 6px;
              border-radius: 4px;
              font-size: 12px;
            }
            
            .play-icon {
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%) scale(1);
              background-color: rgba(0, 0, 0, 0.5);
              color: white;
              border-radius: 50%;
              width: 48px;
              height: 48px;
              display: flex;
              align-items: center;
              justify-content: center;
              opacity: 0;
              transition: opacity 0.3s ease, transform 0.3s ease;
            }
          }
          
          .work-info {
            padding: 12px;
            
            .work-title {
              margin: 0 0 8px 0;
              font-size: 16px;
              font-weight: 500;
              line-height: 1.3;
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
              max-height: 42px;
            }
            
            .work-meta {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 8px;
              
              .creator {
                display: flex;
                align-items: center;
                gap: 6px;
                
                .creator-avatar {
                  width: 24px;
                  height: 24px;
                  border-radius: 50%;
                  object-fit: cover;
                }
                
                .creator-name {
                  font-size: 12px;
                  color: var(--text-color-2);
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                  max-width: 120px;
                }
              }
              
              .stats {
                display: flex;
                gap: 8px;
                font-size: 12px;
                color: var(--text-color-3);
                
                span {
                  display: flex;
                  align-items: center;
                  gap: 4px;
                }
              }
            }
            
            .work-time {
              font-size: 12px;
              color: var(--text-color-3);
            }
          }
        }
      }
      
      .pagination {
        display: flex;
        justify-content: center;
        margin-top: 20px;
      }
    }
    
    .sidebar {
      .sidebar-section {
        margin-bottom: 24px;
        
        h3 {
          font-size: 16px;
          font-weight: 500;
          margin: 0 0 12px 0;
          padding-bottom: 8px;
          border-bottom: 1px solid var(--border-color);
        }
        
        .creator-list {
          .creator-item {
            display: flex;
            align-items: center;
            padding: 8px 0;
            cursor: pointer;
            
            &:hover {
              background-color: var(--hover-color);
            }
            
            .creator-avatar {
              width: 36px;
              height: 36px;
              border-radius: 50%;
              object-fit: cover;
              margin-right: 10px;
            }
            
            .creator-info {
              flex: 1;
              overflow: hidden;
              
              .creator-name {
                font-size: 14px;
                font-weight: 500;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
              }
              
              .creator-followers {
                font-size: 12px;
                color: var(--text-color-3);
              }
            }
          }
        }
        
        .tag-cloud {
          margin-bottom: 12px;
        }
        
        .activity-list {
          .activity-item {
            margin-bottom: 16px;
            border-radius: 8px;
            overflow: hidden;
            background-color: var(--card-color);
            
            .activity-banner {
              height: 100px;
              overflow: hidden;
              
              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }
            
            .activity-info {
              padding: 12px;
              
              .activity-title {
                font-size: 14px;
                font-weight: 500;
                margin-bottom: 4px;
              }
              
              .activity-time {
                font-size: 12px;
                color: var(--text-color-3);
                margin-bottom: 8px;
              }
            }
          }
        }
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 960px) {
  .community-container {
    padding: 10px;
    
    .content-layout {
      grid-template-columns: 1fr;
      
      .sidebar {
        order: -1;
        margin-bottom: 20px;
      }
    }
    
    .community-card {
      .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
        
        .search-box {
          width: 100%;
        }
      }
    }
    
    .works-section {
      .filter-bar {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
        
        .filter-options {
          width: 100%;
          justify-content: space-between;
        }
      }
    }
  }
}
</style> 